/**
 * 
 */
package demo.run;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

import demo.build.RunAntBuild;

/**
 * @author Administrator
 * 
 */
public class RunEmbedTomcatServer {

	private Tomcat embedTomcat;

	private Server embedTomcatserver;
	
	public static void main(String[] args) throws LifecycleException {
		String contextPath = "/00-Pivot-Demo"; 
		String ApplicationPath = "D:\\00-MyProjects\\Workspace\\00-Pivot-Demo\\WebContent";
		String buildXmlFile = "D:\\00-MyProjects\\Workspace\\00-Pivot-Demo\\build.xml";
		
		RunAntBuild antBuild = new RunAntBuild(buildXmlFile);
		antBuild.execute();
		
		RunEmbedTomcatServer server = new RunEmbedTomcatServer(contextPath, ApplicationPath, 9009, 9119);				
		server.startup();
		// server.shutdown();
	}

	public RunEmbedTomcatServer(String contextPath, String ApplicationPath, int startupPort, int shutdownPort) {
		embedTomcat = new Tomcat();
		embedTomcatserver = embedTomcat.getServer();

		embedTomcatserver.addLifecycleListener(new AprLifecycleListener());
		// 注册关闭端口以进行关闭
		embedTomcatserver.setPort(shutdownPort);

		StandardContext standardContext = new StandardContext();
		standardContext.setPath(contextPath); // contextPath
		standardContext.setDocBase(ApplicationPath); // 文件目录位置
		standardContext.addLifecycleListener(new Tomcat.DefaultWebXmlListener());
		// 保证已经配置好了。
		standardContext.addLifecycleListener(new Tomcat.FixContextListener());
		standardContext.setSessionCookieName("t-session");

		embedTomcat.getHost().addChild(standardContext);
		embedTomcat.setPort(startupPort);
	}

	// 启动tomcat，并让tomcat在关闭端口上监听。如果没有最后一句，程序将直接结束。
	// 保证监听之后，tomcat将一直监听关闭事件，待有关闭事件之后才结束当前程序。
	public void startup() throws LifecycleException {
		embedTomcat.start();		
		embedTomcatserver.await();
	}

	public void shutdown() throws LifecycleException {
		embedTomcat.stop();
		embedTomcatserver.stop();
	}
}
